<template>
  <div>
    <div id="carttp">
      <header class="top_bar">
        <a
          @click="gotoPage()"
          class="icon_back"
        ></a>
        <h3 class="cartname">购物车</h3>
      </header>
    </div>

    <main class="cart_box">
      <div
        class="cart_tip clearfix"
        v-if="userId===''"
      >
        <span>登录后可同步电脑与手机购物车中的商品</span>
        <router-link
          to="/login"
          class="login"
        >登录</router-link>
      </div>
      <div
        class="cart_content clearfix"
        v-for="(item,index) in cartDatas"
        :key="item.id"
      >
        <div class="cart_shop clearfix">

          <div class="cart_check_box">
            <div
              :class="item.checked?'check_box_true':'check_box_false'"
              @click="checkThis(item.id)"
            >

            </div>
          </div>
          <div class="shop_info clearfix">
            <img
              v-lazy="item.picUrl"
              alt=""
              class="shop_icon"
              @click="checkThis(item.id)"
            >
            <span
              class="shop_name"
              @click="checkThis(item.id)"
            >{{item.goodsName}}</span>
          </div>

        </div>
        <div class="cart_item">

          <div class="cart_detial_box clearfix">
            <a
              href="#"
              class="cart_product_link"
              @click="checkThis(item.id)"
            >
              <img
                v-lazy="item.picUrl"
                alt=""
              >
            </a>
            <div class="item_names">
              <a href="#">
                <span>{{item.goodsName}}</span>
              </a>
            </div>
            <div class="cart_weight">
              <i class="my_weigth">规格:{{item.specifications}}</i>
              <!-- <span class="my_color">颜色:AT800/16</span> -->
            </div>
            <div class="cart_product_sell">
              <span class="product_money">￥<strong class="real_money">{{item.price}}</strong></span>
              <div class="cart_add clearfix">
                <span
                  class="my_add"
                  @click="cutNum(item.id)"
                >-</span>
                <input
                  :id="item.id"
                  readonly="readonly"
                  class="my_count"
                  :value="item.number"
                >
                <span
                  class="my_jian"
                  @click="addNum(item.id)"
                >+</span>
              </div>
            </div>
            <div class="cart_del clearfix">
              <div class="del_top">
              </div>
              <div
                class="del_bottom"
                @click="deleteThis(item.id,index)"
              >
              </div>
            </div>
          </div>
        </div>

      </div>

    </main>

    <div class="cart_fo">
      <footer class="cart_footer">
        <div class="all_check_box">
          <div class="put_box">
            <div
              :class="checkAllType ? 'checkAll_box' : 'uncheck_box'"
              @click="checkAll()"
            >
            </div>
          </div>
          <span>全选</span>
        </div>
        <div class="count_money_box">
          <div class="heji">
            <strong>合计:</strong>
            <strong>￥</strong>
            <strong style="font-size: 22px;">{{totalMoney}}</strong>
          </div>

          <div class="go_pay">
            <span @click="goPay">去支付</span>
          </div>
        </div>
      </footer>
    </div>
  </div>
</template>
<script>
import { create } from "domain";
import { MessageBox } from "mint-ui";
export default {
  components: {
    MessageBox
  },
  data() {
    return {
      cartDatas: [],
      goodsDatas: [],
      num: [],
      checkAllType: false,
      totalMoney: "",
      userId: "",
      productIds: [],
      nums: [],
      number: 0
    };
  },
  mounted() {
    this.getCartDatas();
  },

  methods: {
    gotoPage() {
      var _this = this;
      _this.$router.push("/home");
    },
    changeNum(itemId, productId) {
      var xx = document.getElementById(itemId).value;
      var x = xx.replace(/[^0-9-]+/, "");
      // console.log(x);
      var thisNum = "";
      this.num.map(function(v) {
        if (v.id == productId) {
          thisNum = v.number;
        }
      });
      if (x < thisNum) {
        let flag = false;
        this.cartDatas = this.cartDatas.map(function(v) {
          if (v.id === itemId) {
            v.number = x;
            if (x == 0) {
              v.number = 1;
            }
            if (v.checked) {
              flag = true;
            }
          }
          return v;
        });
        if (flag) {
          this.computedMoney();
        }
      } else {
        this.cartDatas = this.cartDatas.map(function(v) {
          if (v.id === itemId) {
            v.number = thisNum;
          }
          return v;
        });
        this.computedMoney();
        MessageBox("提示", "超过库存");
      }
    },
    getCartDatas() {
      let _this = this;
      this.$store.dispatch("hideNav");
      if (window.sessionStorage.userInfo) {
        let uObj = JSON.parse(window.sessionStorage.userInfo);
        _this.userId = uObj.id;
        _this.$http
          .get("/mechanismadmin/cart/getCart", {
            params: {
              userId: _this.userId
            }
          })
          .then(
            res => {
              if (res.data.data.cart != undefined) {
                _this.cartDatas = res.data.data.cart;
                _this.num = res.data.data.num;
                _this.goodsDatas = res.data.data.goods;
                this.computedMoney();
              }
            },
            err => {
              console.log(err);
            }
          );
      }
    },

    computedMoney() {
      let myTotalPrice = 0;
      this.cartDatas.map(function(v) {
        if (v.checked) {
          myTotalPrice += v.price * v.number;
        }
      });
      console.log(myTotalPrice);

      this.totalMoney = parseFloat(myTotalPrice).toFixed(2);
    },

    deleteFunction(itemId, index) {
      let _this = this;
      _this.$http
        .get("/mechanismadmin/cart/deleteGoods", {
          params: {
            userId: _this.userId,
            id: itemId
          }
        })
        .then(res => {
          if (res.data.data.deleteFlag === 1) {
            this.cartDatas.splice(index, 1);
            this.computedMoney();
          }
        });
    },

    deleteThis(itemId, index) {
      MessageBox.confirm("确认删除此商品", "提示", {
        showCancelButton: true,
        confirmButtonText: "确认",
        cancelButtonText: "取消"
      })
        .then(() => {
          this.deleteFunction(itemId, index);
        })
        .catch(() => {});
    },

    cutNum(itemId) {
      let flag = false;
      let _this = this;
      _this.cartDatas = _this.cartDatas.map(function(v) {
        if (v.id === itemId) {
          _this.goodsDatas.map(function(s) {
            if (s.product_id === v.productId && v.number > s.min_number) {
              v.number -= s.add_number;
            }
          });
          if (v.checked) {
            flag = true;
          }
        }
        return v;
      });
      if (flag) {
        _this.computedMoney();
      }
    },

    addNum(itemId) {
      let flag = false;
      let _this = this;
      _this.cartDatas = _this.cartDatas.map(function(v) {
        if (v.id === itemId) {
          _this.goodsDatas.map(function(s) {
            if (s.product_id === v.productId && v.number < s.bigNumber) {
              v.number += s.add_number;
            }
          });
        }
        if (v.checked) {
          flag = true;
        }
        return v;
      });
      if (flag) {
        _this.computedMoney();
      }
    },

    checkThis(itemId) {
      this.cartDatas = this.cartDatas.map(function(v) {
        if (v.id === itemId) {
          if (v.checked) {
            v.checked = false;
          } else {
            v.checked = true;
          }
        }
        return v;
      });
      this.computedMoney();
    },

    checkAll() {
      if (this.checkAllType) {
        this.cartDatas = this.cartDatas.map(function(v) {
          v.checked = false;
          return v;
        });
        this.checkAllType = false;
      } else {
        this.cartDatas = this.cartDatas.map(function(v) {
          v.checked = true;
          return v;
        });
        this.checkAllType = true;
      }
      this.computedMoney();
    },
    goPay() {
      for (let i = 0; i < this.cartDatas.length; i++) {
        if (this.cartDatas[i].checked == true) {
          this.productIds += this.cartDatas[i].productId + "@@";
          this.nums += this.cartDatas[i].number + "@@";
        }
      }
      let _this = this;
      _this.$http
        .get("/mechanismadmin/cart/queryNumber", {
          params: {
            productIds: _this.productIds,
            nums: _this.nums
          }
        })
        .then(response => {
          // console.log(response.data.data + "number");
          if (response.data.data === 1) {
            alert("没有库存！");
            this.number = 1;
            this.productIds = [];
            this.nums = [];
          } else {
            for (let i = 0; i < this.cartDatas.length; i++) {
              if (
                this.cartDatas[i].checked == true &&
                this.cartDatas[i].number > 0
              ) {
                window.sessionStorage.cartDatas = JSON.stringify(
                  this.cartDatas
                );
                window.sessionStorage.totalMoney = JSON.stringify(
                  this.totalMoney
                );
                // console.log(this.$store);
                this.$router.push("/pay");
              }
            }
          }
        });
    }
  }
};
</script>
<style>
@import "../assets/css/cart.css";
</style>


